package alingrad.engine.core;

import java.util.TreeMap;

import javax.microedition.khronos.opengles.GL10;

import alingrad.engine.graphics.Sprite;
import alingrad.engine.graphics.Texture;
import alingrad.engine.util.TextureLoader;

public class ResourceLibrary {
	private TreeMap<Integer, Texture> mTextureMap;

	public ResourceLibrary() {
		mTextureMap = new TreeMap<Integer, Texture>();
	}

	public Sprite getSprite(final int ref) {
		return new Sprite(getTexture(ref));
	}

	public Sprite getOrLoadSprite(GL10 gl, final int ref) {
		return getOrLoadSprite(gl, ref, false);
	}

	public Sprite getOrLoadSprite(GL10 gl, final int ref, final boolean collidable) {
		return new Sprite(getOrLoadTexture(gl, ref, collidable));
	}

	public Texture getTexture(final int ref) {
		if (!mTextureMap.containsKey(ref))
			throw new RuntimeException("Texture at " + ref + " has not been loaded!");
		return mTextureMap.get(ref);
	}

	public Texture getOrLoadTexture(GL10 gl, final int ref) {
		return getOrLoadTexture(gl, ref, false);
	}

	public Texture getOrLoadTexture(GL10 gl, final int ref, final boolean collidable) {
		if (mTextureMap.containsKey(ref)) {
			return mTextureMap.get(ref);
		}
		mTextureMap.put(ref, TextureLoader.loadTexture(gl, ref, collidable));
		return mTextureMap.get(ref);
	}

	public void loadTexture(GL10 gl, final int ref) {
		loadTexture(gl, ref, false);
	}

	public void loadTexture(GL10 gl, final int ref, final boolean collidable) {
		mTextureMap.put(ref, TextureLoader.loadTexture(gl, ref, collidable));
	}

	public void clear(GL10 gl) {
		for (Texture texture : mTextureMap.values())
			texture.destroy(gl);
	}
}
